package com.wb.utils

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.util.HashMap
import kotlin.jvm.Throws

/**
 * csdn工具
 *
 * @author 祁雪
 */
class CSDNUtil {

    companion object {

        /**
         * 搜索api
         * https://so.csdn.net/api/v3/search
         * q=搜索词
         * t=all.全站  blog.博客
         * p=1 页码
         * s=0
         * tm=0
         * lv=-1
         * ft=0
         * l=
         * u=
         * ct=-1
         * pnt=-1
         * ry=-1
         * ss=-1
         * dct=-1
         * vco=-1
         * cc=-1
         * sc=-1
         * akt=-1
         * art=-1
         * ca=-1
         * prs=
         * pre=
         * ecc=-1
         * ebc=-1
         * urw=
         * ia=1
         * platform=pc
         * GET方式
         * 参数可缩短为:
         * q=搜索词
         * t=blog
         * p=1
         * platform=pc
         */
        val SEARCH_API = "https://so.csdn.net/api/v3/search"

        @kotlin.jvm.Throws(Exception::class)
        fun searchBlog(key: String): ResultPojo? {

            val result = RestUtil.sendGet(
                SEARCH_API, hashMapOf<String, String>(
                    "q" to key,
                    "t" to "blog",
                    "p" to "1",
                    "platform" to "pc"
                )
            )

            val map = Gson().fromJson(
                result,
                object : TypeToken<HashMap<String, Any>>() {}.type
            ) as HashMap<String, Any>

            if (map.containsKey("result_vos")) {

                val gson = Gson()

                val array = gson.fromJson(
                    gson.toJson(map.get("result_vos")),
                    object : TypeToken<List<ResultPojo>>() {}.type
                ) as List<ResultPojo>

                // 随机选一个
                val pojo = array.get((Math.random() * array.size).toInt())

                // 去除标签
                pojo.title = pojo.title.replace(Regex("<[^>]*>"), "")
                pojo.digest = pojo.digest.replace(Regex("<[^>]*>"), "")
                if (pojo.digest.length >= 50) {
                    pojo.digest = "${pojo.digest.substring(0, 50)}...."
                }
                pojo.url = if (pojo.url.isEmpty()) {
                    ""
                } else {
                    pojo.url.split("?")[0]
                }

                return pojo
            }

            return null

        }

    }

    class ResultPojo {

        var nickname: String = ""

        var title: String = ""

        var digest: String = ""

        var url: String = ""

        override fun toString(): String {
            return "ResultPojo(nickname='$nickname', title='$title', digest='$digest', url='$url')"
        }

    }

}

fun main() {
    println(CSDNUtil.searchBlog("oom"))
}